/*
 *  This is a open source android calculator.
 *  It is maintened by Luis Fernando Junior, Computer Science student @ UNESP, Brazil
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY.
 *  For more information, you can visit the the project repository: http://code.google.com/p/android-opencalc/
 *  
 *  You can send me comments, requests and ideas by e-mail.
 *  luis.fernando.majr@gmail.com
 *  www.luisfernandojr.com
 *  
 *  This app is also available at Android Market
 *  
 *  TO-DO:	Background
 *  		Icon
 *  		Code optimization
 *  
 */

package com.luisfernandojr.calc;

import java.text.DecimalFormat;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Calc extends Activity {
    
	private EditText txt_res;
    private String s_old_ope = "";
	private String s_new_ope = "";
	private char operation = ' ';
	private ArrayList<String> s_history = new ArrayList<String>();
	
	DecimalFormat decimal = new DecimalFormat( "0.####" );
	
	public  AlertDialog dlgmessage;
	private Calc mContext;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    		MenuInflater inflater = getMenuInflater();
    		inflater.inflate(R.menu.menu, menu);
    		return true;
    }
	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
      case R.id.mSobre:
			dlgmessage = new AlertDialog.Builder(mContext)
				.setTitle("About")
				.setMessage("This is a simple (and opensource) android calculator for those who wants to learn android development.\n\nhttp://code.google.com/p/android-opencalc/")
				.setPositiveButton("OK", null).show();
        return true;
      case R.id.mMail:
    	  final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
          emailIntent.setType("plain/text");
          emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"luis.fernando.majr@gmail.com"});
          emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "OpenCalc App");
          emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
          startActivity(Intent.createChooser(emailIntent, "Contact Us"));
        return true;
      case R.id.mSair:
    	  System.exit(0);
        return true;
      default:
        return true;
      }
    }

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.simple);
        mContext = this;

        txt_res = (EditText) findViewById(R.id.txtres);
        
        Button btn_1  = (Button) findViewById(R.id.btn1);
        Button btn_2  = (Button) findViewById(R.id.btn2);
        Button btn_3  = (Button) findViewById(R.id.btn3);
        Button btn_4  = (Button) findViewById(R.id.btn4);
        Button btn_5  = (Button) findViewById(R.id.btn5);
        Button btn_6  = (Button) findViewById(R.id.btn6);
        Button btn_7  = (Button) findViewById(R.id.btn7);
        Button btn_8  = (Button) findViewById(R.id.btn8);
        Button btn_9  = (Button) findViewById(R.id.btn9);
        Button btn_0  = (Button) findViewById(R.id.btn0);
        
        Button btn_add  = (Button) findViewById(R.id.btnadd);
        Button btn_min  = (Button) findViewById(R.id.btnmin);
        Button btn_mul  = (Button) findViewById(R.id.btnmul);
        Button btn_div  = (Button) findViewById(R.id.btndiv);
        Button btn_equ  = (Button) findViewById(R.id.btnequ);
        
        Button btn_sqr  = (Button) findViewById(R.id.btnsqr);
        Button btn_pow  = (Button) findViewById(R.id.btnpow);
        Button btn_100  = (Button) findViewById(R.id.btn100);
        
        Button btn_dot  = (Button) findViewById(R.id.btndot);
        Button btn_cle  = (Button) findViewById(R.id.btncle);
        Button btn_del  = (Button) findViewById(R.id.btndel);
        Button btn_his  = (Button) findViewById(R.id.btnhis);
        Button btn_lay  = (Button) findViewById(R.id.btnlay);
        
        btn_1.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetText("1");
        	}
        });

        btn_2.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetText("2");
        	}
        });
        
        btn_3.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetText("3");
        	}
        });

        btn_4.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetText("4");
        	}
        });
        
        btn_5.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetText("5");
        	}
        });

        btn_6.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetText("6");
        	}
        });

        btn_7.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetText("7");
        	}
        });
        
        btn_8.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetText("8");
        	}
        });
        
        btn_9.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetText("9");
        	}
        });
        
        btn_0.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetText("0");
        	}
        });

        btn_add.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetOperation('+');
        	}
        });

        btn_lay.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		Toast.makeText(getApplicationContext(), "ToDo", Toast.LENGTH_SHORT).show();
        	}
        });

        btn_min.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetOperation('-');
        	}
        });
        
        btn_div.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetOperation('/');
        	}
        });
        
        btn_mul.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetOperation('*');
        	}
        });
        
        btn_pow.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		SetOperation('^');
        	}
        });
        
        btn_sqr.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		
        		if (s_new_ope.length() == 0)
        		{
        			return;
        		}
        		
        		double n2 = new Double(s_new_ope);
        		
        		if (n2 < 0){
        			dlgmessage = new AlertDialog.Builder(mContext)
						.setTitle("Error")
						.setMessage("Cannot perform this operation")
						.setPositiveButton("OK", null).show();
        			return;
        		}
        		
        		if (SetOperation('√')== false)
        		{
        			return;
        		}
        		
        		double dResult = Math.sqrt(n2);
	    		
        		Add2History(txt_res.getText()+" = "+decimal.format(dResult));
        		
        		s_old_ope = "";
	    		s_new_ope = String.valueOf(decimal.format(dResult));
	    		operation = ' ';
	    		
	    		txt_res.setText(decimal.format(dResult));
	    		
	        	}
        });

        btn_del.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		
        		String cRes = "";
        		
        		if (s_new_ope.length() == 0)
        		{
        			if (operation == ' ')
        			{
        				if (s_old_ope.length() == 0)
        				{
        					return;
        				}
        			}
        			else
        			{
        				operation = ' ';
        				s_new_ope = s_old_ope;
        				s_old_ope = "";
        				cRes = s_new_ope;
        			}
        		}
        		else
        		{
        			
        			if (s_old_ope.length() > 0)
        			{
        				cRes = s_old_ope;
        			}
        			
        			if (operation != ' ')
        			{
        				cRes+= " "+operation+" ";
        			}
        				
        			s_new_ope = s_new_ope.substring(0,s_new_ope.length()-1);
        			cRes+= s_new_ope;
        			
        		}
        		
        		txt_res.setText(cRes);
        		
        	}
        });
        
        
        btn_cle.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		operation = ' ';
        		s_old_ope = "";
        		s_new_ope = "";
        		txt_res.setText("");
        		s_history = new ArrayList<String>();
        	}
        });
        
        btn_dot.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		
        		if (s_new_ope.contains(".")==true)
        		{
        			return;
        		}
        		
        		SetText(".");
        		
        	}
        });
        
        btn_his.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
        		
        		Intent it = new Intent(getApplicationContext(),Hist.class);
        		
        		// passing parameter to next activity
        		Bundle b = new Bundle();
        		b.putStringArrayList("history", s_history);
        		it.putExtras(b);
        		
        		startActivity(it);
        	}
        });
        
        btn_equ.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
    		
        		if (operation == ' ')
        		{
        			dlgmessage = new AlertDialog.Builder(mContext)
						.setTitle("Error")
						.setMessage("Choose the operation to perform")
						.setPositiveButton("OK", null).show();
        			return;
        		}
        		
        		if (s_new_ope.length() == 0)
        		{
        			dlgmessage = new AlertDialog.Builder(mContext)
						.setTitle("Error")
						.setMessage("The second operand must be entered")
						.setPositiveButton("OK", null).show();
        			return;
        		}
        		
        		double dResult = 0;
        		double n1 = new Double(s_old_ope);
        		double n2 = new Double(s_new_ope);
        		
        		if (n2 == 0 && operation == '/')
        		{
        			dlgmessage = new AlertDialog.Builder(mContext)
						.setTitle("Error")
						.setMessage("Cannot divide by zero")
						.setPositiveButton("OK", null).show();
        			return;
        		}
        		
        		switch (operation)
        		{
        		case '+':
        			dResult = n1 + n2;
        			break;
        		case '-':
        			dResult = n1 - n2;
        			break;
        		case '*':
        			dResult = n1 * n2;
        			break;
        		case '/':
        			dResult = n1 / n2;
        			break;
        		case '^':
        			dResult = Math.pow(n1,n2);
        			break;
        		}
        		
        		Add2History(txt_res.getText()+" = "+decimal.format(dResult));
        		
        		s_old_ope = "";
        		s_new_ope = String.valueOf(decimal.format(dResult));
        		operation = ' ';
        		
        		txt_res.setText(decimal.format(dResult));
        		
        	}
        });

        btn_100.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View arg0) {
    		
        		if (operation != '+'&& operation != '-' && operation != '*' && operation != '/')
        		{
        			dlgmessage = new AlertDialog.Builder(mContext)
						.setTitle("Error")
						.setMessage("Supported operations : + - * /")
						.setPositiveButton("OK", null).show();
        			return;
        		}
        		
        		if (s_new_ope.length() == 0)
        		{
        			dlgmessage = new AlertDialog.Builder(mContext)
						.setTitle("Error")
						.setMessage("The second operand must be entered")
						.setPositiveButton("OK", null).show();
        			return;
        		}
        		
        		double dResult = 0;
        		double n1 = new Double(s_old_ope);
        		double n2 = new Double(s_new_ope);
        		
        		switch (operation)
        		{
        		case '+':
        			dResult = n1 + (n1*n2/100);
        			break;
        		case '-':
        			dResult = n1 - (n1*n2/100);
        			break;
        		case '*':
        			dResult = n1 * (n2/100);
        			break;
        		case '/':
        			dResult = n1 / (n2/100);
        			break;
        		}
        		
        		Add2History(txt_res.getText()+"% = "+decimal.format(dResult));
        		
        		s_old_ope = "";
        		s_new_ope = String.valueOf(decimal.format(dResult));
        		operation = ' ';
        		
        		txt_res.setText(decimal.format(dResult));
        		
        	}
        });

    }
    
    private boolean SetOperation(char ope)
    {
		
    	if (operation != ' ')
    	{
			dlgmessage = new AlertDialog.Builder(mContext)
				.setTitle("Error")
				.setMessage("Current Operation: "+operation)
				.setPositiveButton("OK", null).show();
			return false;
    	}
    	
    	if (s_new_ope.length() == 0)
    	{
			dlgmessage = new AlertDialog.Builder(mContext)
				.setTitle("Error")
				.setMessage("Enter the first operand before the operation")
				.setPositiveButton("OK", null).show();
			return false;
    	}
    	
    	s_old_ope = s_new_ope;
		s_new_ope = "";
		operation = ope;
		
		txt_res.setText(txt_res.getText()+" "+ope+" ");
		return true;
		
    }
    
    private void Add2History(String entry)
    {
    	s_history.add(entry);
    }
    
    private void SetText(String cDigit)
    {
		s_new_ope+= cDigit;
		txt_res.setText(txt_res.getText()+cDigit);
		return;
    }

}